package com.person.webdemoproject2.fliter;

import com.alibaba.fastjson2.JSON;
import com.person.webdemoproject2.pojo.Result;
import com.person.webdemoproject2.utils.jwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;


import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class loginFliter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String url = request.getRequestURI().toString();
        if (url.contains("login")) {
            log.info("登录操作");
            filterChain.doFilter(request, response);

            return;
        }
        String jwt = request.getHeader("token");

        if (jwt == null) {
            log.info("未登录");
            Result.error("NOT_LOGIN");
            String notLogin = JSON.toJSONString(Result.error("NOT_LOGIN"));
            response.getWriter().write(notLogin);
        }
        try {
            jwtUtils.parseJWT(jwt);
            return;
        } catch (Exception e) {
            log.info("未登录");
            Result.error("NOT_LOGIN");
            String notLogin = JSON.toJSONString(Result.error("NOT_LOGIN"));
            response.getWriter().write(notLogin);
        }
        log.info("令牌解析成功");
        filterChain.doFilter(request, response);
    }

}
